package com.ctl.szmd.szmd.feature_wm.ui.fragment

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.ctl.lib_common.utils.livebus.LiveBus
import com.ctl.szmd.szmd.feature_wm.Constants
import com.ctl.szmd.szmd.feature_wm.R
import com.ctl.szmd.szmd.feature_wm.databinding.FragmentFileDisplayBinding
import com.ctl.szmd.szmd.feature_wm.ui.base.BaseWmBindingFragment
import com.ctl.szmd.szmd.feature_wm.ui.viewmodel.FileDisplayViewModel
import com.tencent.smtt.sdk.QbSdk
import kotlinx.coroutines.launch
import org.json.JSONException
import org.json.JSONObject
import org.koin.android.viewmodel.ext.android.viewModel
import java.io.File
import java.util.*


class FileDisplayFragment : BaseWmBindingFragment<FragmentFileDisplayBinding>() {


    companion object {
        const val PATH = "path" //文件（下载）路径
        const val FILE_NAME = "fileName" //文件名字
        const val OPEN_FILE = "openFile" //0:重新下载并打开；1：打开已有文件
    }

    private val viewModel: FileDisplayViewModel by viewModel()

    override fun getLayoutId(): Int {
        return R.layout.fragment_file_display
    }

    override fun initView() {

        binding.vm = viewModel
        lifecycle.addObserver(viewModel)

        val path = arguments?.getString(PATH, "") ?: ""
        val name = arguments?.getString(FILE_NAME, "") ?: ""

        val list = arrayOfNulls<String>(1)
        list[0] = "android.permission.WRITE_EXTERNAL_STORAGE"
        this@FileDisplayFragment.requestPermissions(list, 105)

        lifecycleScope.launch {
            viewModel.getDownLoadFile(path, name)
        }

        LiveBus.get(Constants.LIVE_BUS_FILE_DOWNLOAD_FINISH_OPEN, File::class.java)
            .observe(this, androidx.lifecycle.Observer {
                openFileReader(it.absolutePath)
            })
    }

    private fun openFileReader(pathName: String?) {
        val params = HashMap<String, String>()
        params["style"] = "1"
        params["topBarBgColor"] = "#b80b0f"
        val obj = JSONObject()
        try {
            obj.put("pkgName", requireActivity().application.packageName)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        params["menuData"] = obj.toString()
        val v = QbSdk.getMiniQBVersion(requireActivity())
        LogUtils.i(v)
        val ret = QbSdk.openFileReader(requireActivity(), pathName, params) { s ->
            LogUtils.e(s)
            if (s == "fileReaderClosed") {
                findNavController().navigateUp()
            }
        }
        //1:用 QQ 浏览器打开  2:用 MiniQB 打开  3:调起阅读器弹框   -1:filePath 为空 打开失败
        if (ret == -1) {
            ToastUtils.showShort("文件打开失败")
        } else if (ret == 3) {
            findNavController().navigateUp()
        }
        LogUtils.e(ret)
    }
}